//
//  GBAppDelegate.m
//  PngOK
//
//  Created by wanglidong on 14-4-30.
//  Copyright (c) 2014年 GoldenBull. All rights reserved.
//

#import "GBAppDelegate.h"
#import "GBNSUtils.h"
#import "GBFileManager.h"

@implementation GBAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    
    [GBNSUtils addTarget:self action:@selector(onPickInputPath) forControl:_buttonInputPath];
    [GBNSUtils addTarget:self action:@selector(onPickOutputPath) forControl:_buttonOutputPath];
    [GBNSUtils addTarget:self action:@selector(onRun) forControl:_buttonRun];
    [GBNSUtils addTarget:self action:@selector(showInputHelp:) forControl:_buttonInputHelp];
    [GBNSUtils addTarget:self action:@selector(showOutputHelp:) forControl:_buttonOutputHelp];
    
    [_tableList setDataSource:self];
    [_tableList setDelegate:self];
    [[_tableList headerView] setNeedsDisplay:YES];
    [_tableList setAllowsMultipleSelection:NO];
    
    [_textFieldInputPath becomeFirstResponder];
    
    [self.window becomeKeyWindow];
    [self.window becomeMainWindow];
    [self.window setReleasedWhenClosed:YES];
    
    [self setDefaultOutPath];
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
{
    return YES;
}

- (void)setDefaultOutPath
{
    _textFieldOutputPath.stringValue = [[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"output"];
}

- (void)onPickInputPath
{
    [GBNSUtils openItem:[NSArray arrayWithObjects:@"png", nil] completionHandler:^(NSInteger result, NSArray *urls) {
        
        if (1 != result) {
            return ;
        }
        
        [self resetImage];
        
        self.inputFiles = [NSMutableArray array];
        
        self.inputFilesSize = 0;

        if ([urls count] <=0 ) {
            return;
        }

        NSString *root = nil;
        
        NSUInteger total = [urls count];

            for (NSURL *url in urls)
            {
                NSString *path = [url relativePath];
                
                if (!root)
                {
                    // 只有一个
                    if ( total == 1 )
                    {
                        root = path;
                    }
                    else
                    {
                        root = [path stringByDeletingLastPathComponent];
                    }
                }
                
                GBFileType type = [GBFileManager typeOfItemAtPath:path];
                if (GBFileTypeFolder == type)
                {
                    // 遍历所有子目录搜索 .png文件
                    filesHasExtension(root, [path UTF8String], @"png", _inputFiles, &_inputFilesSize);
                }
                else if (GBFileTypeFile == type)
                {
                    addFileToList([path stringByDeletingLastPathComponent], [path stringByDeletingLastPathComponent], [path lastPathComponent], [GBFileManager fileSizeOfItemAtPath:path], _inputFiles, &_inputFilesSize);
                }

            }

        [_textFieldInputPath setStringValue:root];
        
        [_textFieldOutputPath becomeFirstResponder];
        
        [_tableList reloadData];
        
        [self showLogOfOldSize:_inputFilesSize andNewSize:_inputFilesSize];

    }];

}

- (void)onPickOutputPath
{
    [GBNSUtils openFolder:YES completionHandler:^(NSInteger result, NSString *path) {

        [_textFieldOutputPath setStringValue:path];
        
        [_textFieldOutputPath resignFirstResponder];
        
//        [_tableList becomeFirstResponder];
    }];
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    return [_inputFiles count];
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSMutableDictionary *item = [_inputFiles objectAtIndex:row];
    
    NSString *identifier = [tableColumn identifier];
    
    if ([identifier rangeOfString:@"size"].location != NSNotFound) {
        return stringWithSizeAvoidZero([[item objectForKey:identifier] longLongValue]);
    }

    return [item objectForKey:identifier];
}

-(void)tableView:(NSTableView *)tableView sortDescriptorsDidChange:(NSArray *)oldDescriptors
{
    NSArray *newDescriptors = [tableView sortDescriptors];
    [_inputFiles sortUsingDescriptors:newDescriptors];
    //"results" is my NSMutableArray which is set to be the data source for the NSTableView object.
    [tableView reloadData];
}

- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)row
{
    NSMutableDictionary *item = [_inputFiles objectAtIndex:row];
    
    if ([[item objectForKey:@"percent"] isEqualToString:@"error"]) {
        [self showErrorAlert];
    }
    else
    {
        [self showImage:[item objectForKey:@"fullPath"] andImage:[item objectForKey:@"outPath"]];
    }

    return YES;
}

- (void)setUIEnabled:(BOOL)enabled
{
    [_buttonInputPath setEnabled:enabled];
    [_buttonOutputPath setEnabled:enabled];
    [_buttonRun setEnabled:enabled];
    [_checkBoxReplace setEnabled:enabled];
}

- (void)onRun
{
    [self.progressIndicator startAnimation:self.progressIndicator];
    
    BOOL bReplaceMode = ([_checkBoxReplace state] == NSOnState);
    
    [self resetImage];

    [self setUIEnabled:NO];
 
    // 对路径容错
    if ([[_textFieldOutputPath stringValue] isEqualToString:[_textFieldInputPath stringValue]]
        || [[_textFieldOutputPath stringValue] length] < 1) {
        
        [self setDefaultOutPath];
        
    }

    // ./pngquant ../testpngs/dengji.png --output ../testpngs/new_dj.png
    NSString *res = [[NSBundle mainBundle] resourcePath];
    NSString *pngquant = [res stringByAppendingPathComponent:@"pngquant"];
    NSString *outRootPath = [_textFieldOutputPath stringValue];
    //NSLog(@"outRootPath is : %@",outRootPath);
    NSString *outExt = @"out";

    __block NSInteger count = 0;

    __block double sumSizeNew = _inputFilesSize;

    NSUInteger total = [_inputFiles count];
    for (NSMutableDictionary *item in _inputFiles)
    {
        NSString *fullpath = [item objectForKey:@"fullPath"];
        //NSLog(@"relativePath : %@",[item objectForKey:@"relativePath"]);
        NSString *outFolder = [outRootPath stringByAppendingString:[item objectForKey:@"relativePath"]];
        
        NSString *name = [item objectForKey:@"name"];
        //name = [name stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        // 覆盖模式

        if (bReplaceMode)
        {
            name = [name stringByAppendingPathExtension:outExt];
        }
        
        NSString *outPath = [outFolder stringByAppendingPathComponent:name];

        // 输出目录可能不存在
        [GBFileManager newFolder:outFolder force:NO];
        
        // 输出文件可能已存在
        [GBFileManager removeItemAtPath:outPath];
        
        NSString *bash = [NSString stringWithFormat:@""
                          "%@ %@ --output %@"
                          ,pngquant,fullpath,outPath
                          ];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSString *oplog = [GBNSUtils runCommand:bash];
            NSLog(@"%@",oplog);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                // 要检查压缩是否出错
                if (![GBFileManager isExist:outPath isDirectory:NO])
                {
                    NSLog(@"%@",outPath);
                    [item setObject:@"error" forKey:@"percent"];
                }
                else
                {
                    // 刷新UI
                    double new_size = [GBFileManager fileSizeOfItemAtPath:outPath];
                    [item setObject:[NSNumber numberWithDouble:new_size] forKey:@"newsize"];
                    double old_size = [[item objectForKey:@"size"] doubleValue];
                    double percent = 100-new_size*100 / old_size;
                    [item setObject:[NSString stringWithFormat:@"%0.1f%%",percent] forKey:@"percent"];
                    
                    // 总共压缩体积
                    sumSizeNew = sumSizeNew - old_size + new_size;

                    // 覆盖模式
                    if (bReplaceMode)
                    {
                        NSString *newPath = [outPath stringByDeletingPathExtension];
                        // 原图移动到输出目录
                        [GBFileManager moveItemAtPath:fullpath toPath:newPath force:YES];

                        // 压缩图移动到原图目录
                        [GBFileManager moveItemAtPath:outPath toPath:fullpath force:YES];

                        // 设置
                        [item setObject:newPath forKey:@"outPath"];
                    }
                    else
                    {
                        [item setObject:outPath forKey:@"outPath"];
                    }
                }
                
                [_tableList reloadData];
                
                [self showLogOfOldSize:_inputFilesSize andNewSize:sumSizeNew];
                
                // all done
                if (++count >= total) {
                    [self.progressIndicator stopAnimation:self.progressIndicator];

                    [self setUIEnabled:YES];
                }
            });
            
        });

    }
}

- (void)showLogOfOldSize:(double)sizeOld andNewSize:(double)sizeNew
{
    [_textFieldOutputLog setStringValue:[NSString stringWithFormat:@"原始图总计:%@\t\t压缩后总计:%@\t\t压缩比:%0.0f%%",
                                         stringWithSizeAllowB(sizeOld),
                                         stringWithSizeAllowB(sizeNew),
                                         100.0-sizeNew*100.0 / sizeOld
                                         ]];
}

- (void)resetImage
{
    [_imageViewOld setImage:nil];
    [_imageViewNew setImage:nil];
}

- (void)showImage:(NSString *)pathOld andImage:(NSString *)pathNew
{
    //NSLog(@"pathOld : %@",pathOld);
    if (pathOld.length < 1) {
        
        [_imageViewOld setImage:nil];
        return;
    }
    NSImage *imageOld = [[NSImage alloc]initWithContentsOfFile:pathOld];

    [_imageViewOld setImage:imageOld];
    
    [_textFieldSizeOld setStringValue:[NSString stringWithFormat:@"%0.0fX%0.0f",imageOld.size.width,imageOld.size.height]];
    
    unsigned long long fileSize = [GBFileManager fileSizeOfItemAtPath:pathOld];
    
    [_textFieldFileSizeOld setStringValue:stringWithSizeAllowB(fileSize)];
    
    
    //NSLog(@"pathNew : %@",pathNew);
    if (pathNew.length < 1) {
        
        [_imageViewNew setImage:nil];
        return;
    }
    NSImage *imageNew = [[NSImage alloc]initWithContentsOfFile:pathNew];
    [_imageViewNew setImage:imageNew];

    [_textFieldSizeNew setStringValue:[NSString stringWithFormat:@"%0.0fX%0.0f",imageNew.size.width,imageNew.size.height]];
    
    fileSize = [GBFileManager fileSizeOfItemAtPath:pathNew];
    
    [_textFieldFileSizeNew setStringValue:stringWithSizeAllowB(fileSize)];
}



#pragma mark - menu
#pragma mark error
- (void)showErrorAlert
{
    NSLog(@"%s",__PRETTY_FUNCTION__);
    
    NSAlert *alert = [[NSAlert alloc] init];
    
    [alert setAlertStyle:NSInformationalAlertStyle];
    
    [alert setMessageText:
     @"error:压缩该文件失败.\n"
     "可能原因:路径和文件名不能带空格!"];
    
    [alert addButtonWithTitle:@"关闭帮助"];
    
    NSInteger result = [alert runModal];
    
    if (result == NSAlertFirstButtonReturn)
    {
        return;
    }
}
#pragma mark help
- (IBAction)showHelp:(id)sender
{
    [self showFaq:@"FAQ"];
}

- (IBAction)showInputHelp:(id)sender
{
    [self showFaq:@"faqin"];
}
- (IBAction)showOutputHelp:(id)sender
{
    [self showFaq:@"faqout"];
}

- (void)showFaq:(NSString *)name
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:name ofType:@"html"];
    NSURL* fileURL = [NSURL fileURLWithPath:filePath];
    [[NSWorkspace sharedWorkspace] openURL:fileURL];
}

@end
